package sqs.ejb.sessionbean;

import java.util.List;

import javax.ejb.Stateless;

import sqs.dataaccess.DaoFactory;
import sqs.dataaccess.UserDao;
import sqs.exception.DataAccessException;
import sqs.exception.UserNotFoundException;
import sqs.model.User;

/**
 * @author kjleng
 *
 */
@Stateless(name = "UserEJB", mappedName = "ejb/UserJNDI")
public class UserBean implements UserMgr{
	private UserDao userDao = DaoFactory.getInstance(DaoFactory.HIBERNATE).getUserDao();
	
	public void initialize() {
		userDao = DaoFactory.getInstance(DaoFactory.HIBERNATE).getUserDao();
	}
	
	public User getUserByUserName(String username)throws UserNotFoundException{
		User u = null;
		try {
			u = userDao.getUserByUsername(username);
			if (u == null) {
				throw new UserNotFoundException();
			}
		} catch (DataAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return u;
	}
	
	public void createUser(User user) {
		try {
			userDao.createUser(user);
		} catch (DataAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public List<User> getAllUsers() {
		List<User> users = null;
		try {
			users = userDao.getAllUsers();
		} catch (DataAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return users;
	}
	
	public void removeUser(User user) {
		try {
			userDao.removeUser(user);
		} catch (DataAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void updateUser(User user) throws UserNotFoundException{
		try {
			User u = userDao
					.getUserByUsername(user.getUserId());
			
			if (u == null) {
				throw new UserNotFoundException();
			}else{
				userDao.updateUser(user);
			}
		} catch (DataAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
